package com.ignou.mca.login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ignou.mca.datasource.DatabaseOperations;

/**
 * Servlet implementation class ForgotPassword
 */
public class ForgotPassword extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
    DatabaseOperations dbOps = new DatabaseOperations();  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ForgotPassword() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
    	String userName = request.getParameter("userName");
    	String question = dbOps.getSecutiryQuestion(userName);
    	PrintWriter pw = response.getWriter();
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-cache");
    	pw.println(question);
	}
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String secAns = request.getParameter("securityAnswer");
		String userName = request.getParameter("userName");
		String email = request.getParameter("emailId");
		ServletContext ctx = getServletContext();
		
		String isSuccess = dbOps.forgotPassword(userName, secAns,email);
		if(isSuccess!=null)
		{
			request.setAttribute("password", isSuccess);
			ctx.getRequestDispatcher("./ForgotPasswordSuccess.jsp").forward(request, response);;
		}else
		{
			request.setAttribute("ErrorMessage", "Unable to retrive password. Please contact administrator.");
			ctx.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		}
	}
}
